import { Component, OnInit, Inject, ViewChild, ElementRef, Input, Output  } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router'; 
import { AccountManageService } from "./account-manage.service";
import { AppPaginationComponent, PaginationModel } from '../../../widgets/pagination/pagination.component';
import { environment } from '../../../../environments/environment';
import { Util } from "../../../common/util";
import * as moment from 'moment';
import * as _ from 'lodash';
import { FileUploader } from "ng2-file-upload";

@Component({
	selector: 'deposit-account-manage',
	templateUrl: './account-manage.component.html',
	styleUrls: ['./account-manage.component.scss'],
	providers:[AccountManageService]
})
export class AccountManageComponent implements OnInit {
	public $ = window['$'];
	// 列表当前页全选标记
	public isCheckedAll = false;
	// 是否为ID查询
	public displayModel = 'all';
	// 账户
	public accountOne: any= {};
    // 账户列表
	public accountList: Array<any>;
	// 基金信息列表
	public fundInfoList: Array<any>;
	// 定期存款信息列表
	public tradeInfoList: Array<any>;
	// 获取定存列表
	public searchBody: any= {
		depositId: "",
		page: 1,  
		pageSize: environment.pageSize
	};
	// 定期存款存单信息
	public tradeInfoBody: any= {
		vcFundCode: "",
		page: 1,  
		pageSize: environment.pageSize
	};
	// 历史交易列表
	public tradeListBody: any= {
		page: 1,  
		pageSize: environment.pageSize
	};
    // 编辑账户
	public editAccountInfo: any = {};
    // 新增账户
	public account: any= {
		fundno: "",                      // 基金内码
		empid: "",                       // 委托开户人
		fundname: "",                    // 基金名称
		fundcode: "",                    // 基金代码
		amount: "",                      // 定存金额
		intrate: "",                     // 定存利率
		currencyName: "",                // 币种名称
		zhmaxpay: "",                    // 大额支付号
		zhcode: "",                      // 银行帐户号
		zhname: "",                      // 银行账户名
		fullbankkname: ""                // 银行全称
	};
    // 初始化定义uploader变量,用来配置input中的uploader属性
    public uploader: FileUploader = new FileUploader({});
    // 上传文件的名称
	public uploadFileName: any= "";
	// 选择文件状态
	public fileStatus= false;
	// 分页配置
	public pageInfo: PaginationModel = {
		currentPageNum: 1,
		totalPages: 1,
        pageSize: 10,
        total: 0,
        pagesShow: 5,
        startRow: 0,
        endRow: 0,
		pageList: [5, 10, 25, 50, 100]
	}
	// 历史交易分页配置
	public tradeInfoPage: PaginationModel = {
		currentPageNum: 1,
		totalPages: 1,
        pageSize: 10,
        total: 0,
        pagesShow: 5,
        startRow: 0,
        endRow: 0,
		pageList: [5, 10, 25, 50, 100]
	}
	// 历史交易分页配置
	public tradeListPage: PaginationModel = {
		currentPageNum: 1,
		totalPages: 1,
        pageSize: 10,
        total: 0,
        pagesShow: 5,
        startRow: 0,
        endRow: 0,
		pageList: [5, 10, 25, 50, 100]
	}
	// 分页组件
	@ViewChild(AppPaginationComponent)
	public paginationComponent: AppPaginationComponent;

	constructor(public accountManageService: AccountManageService,public router:Router) {	
	}
	// 初始化列表
	ngOnInit() {
		this.getAccountInfo();
	}
	// 获取账户列表
	getAccountInfo(){
		let that = this;
		this.searchBody.page= this.pageInfo.currentPageNum;
		this.searchBody.pageSize= this.pageInfo.pageSize;
		if (this.searchBody.depositId == "") {
			this.accountManageService.getAccountInfo(this.searchBody).subscribe(data=> {
				if(data){
					that.accountList = _.pull(data.list,null);
					that.pageInfo.totalPages = data.pages;          // 总页数
					that.pageInfo.total= data.total;                // 数据总个数
					that.displayModel= 'all';
					that.isCheckedAll= false;
				}
				else{
					window['swal']("失败","数据获取失败！","error");
				}
				console.log("总记录数："+that.pageInfo.total);
			});
		}else{   // 单个账户
			this.accountManageService.getAccount(this.searchBody.depositId).subscribe(data=> {
				if (data){
					that.accountOne = _.pull(data,null);
					that.editAccountInfo= _.clone(that.accountOne);
					that.displayModel= 'one';
				}else{
					window['swal']("失败","查询失败！","error");
					that.reset();
				}
			})
		}
	}
	// 根据页码获取列表
	getCurrentPageNum(currentPageNum: number) {
		this.pageInfo.currentPageNum = currentPageNum;
		this.getAccountInfo();
		this.isCheckedAll= false;
	}
	// 重置查询ID
	reset(){
		this.searchBody.depositId= "";
		this.pageInfo.currentPageNum= 1;
	}
/////////////////////////////////////////////////////////////////////////////////////////////////////
	// 新增用户
	addAccount(){
		let that = this;
		// 获取银行全程
		this.account.fullbankkname = this.$('#bank').val() + this.$('#fbank').val();
		window["swal"](
			{
				title: "提示！",
				text: "是否确定新增 "+this.account.fundname+" 账户?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			    function(isConfirm) {
					if (isConfirm) { // 确认
						that.accountManageService.addAccount(that.account).subscribe(data => {
							if(data) {
								window["swal"]("成功", "新增成功", "success");
								//that.reset();
								that.resetAddInfo();
								that.$("#openAccountModal").modal('toggle');    // 隐藏新增模版
								that.getAccountInfo();                          // 重新加载列表数据
							}
						});
					} else { 
					// 取消
				}
			}
		);
	}
	// 新增获取基金信息列表
	getFundInfoList(){
		let that = this;
		this.accountManageService.getFundInfoList().subscribe(data=> {
			if (data) {
				that.fundInfoList= _.pull(data,null);
				that.toggleModal('FundListModal');
			}
		})
	}
	// 新增确认选择基金信息
	getFundInfo(fundInfo){
		this.account.fundname= fundInfo.vcFundName;
		this.account.fundcode= fundInfo.vcFundCode;
		this.toggleModal('FundListModal');
	}
	// 重置新增账户信息
	resetAddInfo(){
		this.$('#bank').val("");
		this.$('#fbank').val("");
		this.account.fundname= "";
		this.account.empid= "";
		this.account.fundno= "";
		this.account.fundcode= "";
		this.account.amount= "";
		this.account.intrate= "";
		this.account.currencyName= "";
		this.account.zhmaxpay= "";
		this.account.zhcode= "";
		this.account.zhname= "";
		this.account.fullbankkname= "";
	}
/////////////////////////////////////////////////////////////////////////////////////////////////////
	// 编辑账户信息
	editAccount(){
		let that = this; 
		window["swal"]({
			title: "提示",
			text: "是否要更新账户 "+ this.editAccountInfo.vcFundName+ " 的信息?",
			type: "info",
			confirmButtonText: "确认",
			confirmButtonColor: "#DD6B55",
			cancelButtonText: "取消",
			showCancelButton: true,
			closeOnConfirm: false,
			closeOnCancel: true,
			showLoaderOnConfirm: true
		},
		function(isConfirm) { 
			if(isConfirm){
				that.accountManageService.editAccount(that.editAccountInfo).subscribe(data => {
					if(data) {
						window["swal"]("成功", "更新成功","success");
						that.getAccountInfo(); 
						that.$("#accountModal").modal('toggle');
					}else{
						window["swal"]("失败", "更新失败","error");
					}
				});
			} else {  
				// 取消
		    }
		}
	)}
////////////////////////////////////////////////////////////////////////////////////////////////////
	// 删除单个账户
	delAccount(delaccountlist?){
		let that = this;
		if (delaccountlist) {
			window["swal"]({
				title: "确定?",
				text: "是否确定删除 " +delaccountlist.vcFundName + " 账户?",
				type: "warning",
				confirmButtonText: "确认",
				confirmButtonColor: "#c9302c",
				showCancelButton: true,
				cancelButtonText: "取消",
				closeOnConfirm: false,
				closeOnCancel: true,
				showLoaderOnConfirm: true
			},
			function(isConfirm) {
				if (isConfirm) {
					that.accountManageService.delAccount(delaccountlist.lDepositNo).subscribe(data => {
						if(data) {
							window["swal"]("删除成功", "", "success");
							//that.reset();
							that.getAccountInfo();
							that.displayModel= 'all';
							that.isCheckedAll= false;
						}
					});
				} else {
						
				}
			});
		// 指定ID删除
		}else{
			window["swal"]({
				title: "确定?",
				text: "是否确定删除 " +this.editAccountInfo.vcFundName + " 账户?",
				type: "warning",
				confirmButtonText: "确认",
				confirmButtonColor: "#c9302c",
				showCancelButton: true,
				cancelButtonText: "取消",
				closeOnConfirm: false,
				closeOnCancel: true,
				showLoaderOnConfirm: true
			},
			function(isConfirm) {
				if (isConfirm) {
					that.accountManageService.delAccount(that.editAccountInfo.lDepositNo).subscribe(data => {
						if(data) {
							window["swal"]("删除成功", "", "success");
							//that.reset();                              // 重置查询
							that.getAccountInfo();                     // 重置列表信息
							that.displayModel= 'all';                  // 重置面板显示
							that.isCheckedAll= false;                  // 重置全选按钮
						}
					});
				} else {
					
				}
			})
		}	
	}
    // 删除一个或多个账户
	delAccountMore(){
	
		let that = this;
		let len=this.$('input[name="checkbox"]:checked');
		if(len.length>0){
			window["swal"]({
				title: "确定?",
				text: "是否要删除所选账户?",
				type: "warning",
				confirmButtonText: "确认",
				confirmButtonColor: "#c9302c",
				showCancelButton: true,
				cancelButtonText: "取消",
				closeOnConfirm: false,
				closeOnCancel: true,
				showLoaderOnConfirm: true
			},function(isConfirm) {
				if(isConfirm){
					_.forEach(that.accountList, item=> {
						if(item.isChecked){
							that.accountManageService.delAccount(item.lDepositNo).subscribe(data=> {
								if(data){
									window["swal"]("删除成功", "", "success");
									//that.reset();   
									that.getAccountInfo();
									that.isCheckedAll= false;
									that.displayModel= 'all';
								}
							})
						}
					})
				}
			})
		}else{
			window["swal"]({
				title: "注意!",
				text: "请选择要删除的信息",
				type: "info",
				confirmButtonText: "返回",
				confirmButtonColor: "#00EEEE"
			})
			that.isCheckedAll= false;
		}
	}
	// 全选或全不选
	checkedAll(){
		if (this.isCheckedAll) {                      // 更新为全选
			_.forEach(this.accountList, item => {
				item.isChecked = true;
			});
		} else {                                      // 更新为全不选
			_.forEach(this.accountList, item => {
				item.isChecked = false;
			});
		}
	}
/////////////////////////////////////////////////////////////////////////////////////////////////////
	// 获取上传文件的名称
	selectedFileOnChanged(event: any){
		this.uploadFileName= event.target.value;
		this.fileStatus= true;
		}
	// 上传文件
	uploadFile(){
		let that = this;
		let fileItem = _.last(this.uploader.queue);
		fileItem.url = 'http://legiontest.zhuwenda.com:12042/TimeDeposit/InputFile/'+this.editAccountInfo.lDepositNo+'?token=2';
		fileItem.method = "POST";
		fileItem.alias = this.uploadFileName;
		// fileItem.headers = [{name: 'token', value: sessionStorage.getItem('username')}];

		// 开始上传
		fileItem.upload(); 

		// 上传一个文件成功的回调
		fileItem.onSuccess = function (response, status, headers) {
			let resVal = JSON.parse(response);
			// 上传文件成功,返回的code,一般0代表成功
			if (resVal.code + "" === "0") {
				// 上传文件后获取服务器返回的数据
				window["swal"]("成功", "导入成功", "success");
				// 上传成功后清空文件上传队列
				that.clearFileQueue();
			}else{
				window["swal"]("失败", "导入失败", "error");
				that.clearFileQueue();
			}
		};

		// 接口暂时不能用
		window["swal"]("sorry", "接口暂时不能用", "success");
	}
	// 清除FileUploader上传队列中的所有文件
	clearFileQueue() {
		this.uploader.clearQueue();
		this.fileStatus= false;
		this.$('#XCFile').val("");
	}
	// 文件下载
	downLoadFile(accountlist?){
		let that = this;
		if (accountlist) {
			window["swal"]({
				title: "提示！",
				text: "是否确定下载 "+accountlist.vcFundName+" 的资料？",
				type: "info",
				confirmButtonText: "确认",
				confirmButtonColor: "#c9302c",
				cancelButtonText: "取消",
				showCancelButton: true,
				closeOnConfirm: false,
				closeOnCancel: true,
				showLoaderOnConfirm: true
			},function(isConfirm) {
				if(isConfirm){
					that.accountManageService.downLoadFile(accountlist.vcAttach).subscribe(data=> {
						if(data){
							window["swal"]("成功", "下载成功", "success");
						}else{
							window["swal"]("失败", "无文件下载", "error");
						}
					})
				}
			})
		}else{
			window["swal"]({
				title: "提示！",
				text: "是否确定下载 "+this.editAccountInfo.vcFundName+" 的资料？",
				type: "info",
				confirmButtonText: "确认",
				confirmButtonColor: "#c9302c",
				cancelButtonText: "取消",
				showCancelButton: true,
				closeOnConfirm: false,
				closeOnCancel: true,
				showLoaderOnConfirm: true
			},function(isConfirm) {
				if(isConfirm){
					that.accountManageService.downLoadFile(that.editAccountInfo.vcAttach).subscribe(data=> {
						if(data){
							window["swal"]("成功", "下载成功", "success");
						}else{
							window["swal"]("失败", "无文件下载", "error");
						}
					})
				}
			})
		}
	}
/////////////////////////////////////////////////////////////////////////////////////
	// 基金经理确认
	managerConfirm(accountinfo){
		let that = this;
		window["swal"](
			{
				title: "提示！",
				text: "是否确认 "+accountinfo.vcFundName+" 信息?",
				type: "info",
				confirmButtonText: "确认",
			    confirmButtonColor: "#DD6B55",
			    showCancelButton: true,
			    cancelButtonText: "取消",
			    closeOnConfirm: false,
			    closeOnCancel: true,
                showLoaderOnConfirm: true
			},
			    function(isConfirm) {
					if (isConfirm) {
						that.accountManageService.managerConfirm(accountinfo.lDepositNo).subscribe(data => {
							if(data == true) {
								window["swal"]("成功", "已确认", "success");
								that.getAccountInfo();                         
							}
						})
					}
				} 
		)
	}
	// 定期存款存单信息
	tradeInfo(){
		this.displayModel = 'tradeInfo';
	}
	// 查询定期存款存单信息
	getTradeInfo(){
		let that = this;
		this.tradeInfoBody.page= this.tradeInfoPage.currentPageNum;
		this.tradeInfoBody.pageSize= this.tradeInfoPage.pageSize;
		this.accountManageService.getTradeInfo(this.tradeInfoBody).subscribe(data=> {
			if(data){
				that.tradeInfoList = _.pull(data.list,null);
				that.tradeInfoPage.totalPages = data.pages;          // 总页数
				that.tradeInfoPage.total= data.total;                // 数据总个数
				that.displayModel= 'tradeInfo';
			}
			else{
				window['swal']("失败","请输入基金代码！","warning");
			}
			console.log("总记录数："+that.tradeInfoPage.total);
		});
	}
	// 根据页码获取定期存款信息
	getTradeInfoPageNum(currentPageNum: number) {
		this.tradeInfoPage.currentPageNum = currentPageNum;
		this.getTradeInfo();
		this.displayModel= 'tradeInfo';
	}
	resettradeInfo(){
		this.tradeInfoBody.vcFundCode = "";
	}
	// 历史交易
	getTradeList(){
		let that = this;
		this.displayModel= 'tradeList';
		this.tradeListBody.page= this.tradeListPage.currentPageNum;
		this.tradeListBody.pageSize= this.tradeListPage.pageSize;
		this.accountManageService.getTradeList(this.tradeListBody).subscribe(data=> {
			if(data){
				that.accountList = _.pull(data.list,null);
				that.tradeListPage.totalPages = data.pages;          // 总页数
				that.tradeListPage.total= data.total;                // 数据总个数
			}
			else{
				window['swal']("失败","数据获取失败！","error");
			}
			console.log("总记录数："+that.tradeListPage.total);
		});
	}
	// 根据页码获取历史交易列表
	getTradeListPageNum(currentPageNum: number) {
		this.tradeListPage.currentPageNum = currentPageNum;
		this.getTradeList();
		this.isCheckedAll= false;
		this.displayModel= 'tradeList';
	}
    // 返回
	reBack(){
		this.displayModel = 'all';
		this.getAccountInfo();
		this.tradeInfoBody.vcFundCode = "";
	}
	// 弹出框
    toggleModal(id,accountlist?) {
		let formatedId = "#" + id;
		if(accountlist){
			this.editAccountInfo= _.clone(accountlist);   // 编辑信息
		}
		this.$(formatedId).modal('toggle');
	}
	
	look(){
		window["swal"]("sorry", "接口暂时无法使用!", "success");
	}
}
